import { areaList } from "@vant/area-data";
const computedBehaviors = require("miniprogram-computed");
Component({
  options: {
    styleIsolation: "shared",
  },
  behaviors: [computedBehaviors],
  properties: {
    timePopupShow: Boolean,
    areaPopupShow: Boolean,
    city: String,
    county: String,
  },
  data: {
    timeColumns: ["本月", "本季", "本年"],
  },
  lifetimes: {
    created() {},
    attached() {
      this.getAreaList();
    },
    moved() {},
    detached() {},
  },
  watch: {
    areaPopupShow: function (areaPopupShow) {
      if (areaPopupShow) {
        this.setArea();
      }
    },
  },
  methods: {
    /**
     * 定位到当前选中的市区
     */
    setArea() {
      const { city, county } = this.properties;
      const areaPicker = this.selectComponent("#area-picker");
      areaPicker.setColumnValues(1, this.data.list[city]);
      areaPicker.setValues([city, county]);
    },
    /**
     * 获取市与区列表数据
     */
    getAreaList() {
      const { city_list, county_list } = areaList;
      let list = {},
        i = 0,
        countys = Object.entries(county_list),
        len = countys.length;
      for (const [key, value] of Object.entries(city_list)) {
        list[value] = [];
        const cityStr = key.substring(0, 4);
        while (i < len) {
          const countyKey = countys[i][0];
          const county = countys[i][1];
          if (countyKey.startsWith(cityStr)) {
            list[value].push(county);
            i++;
          } else {
            break;
          }
        }
      }
      const areaColumns = [
        {
          values: Object.keys(list),
        },
        {
          values: list["北京市"],
          defaultIndex: 0,
        },
      ];
      this.setData({ list, areaColumns });
    },
    /**
     * 切换市区
     * @param {*} e
     */
    onAreaChange(e) {
      const { picker, value, index } = e.detail;
      const { list } = this.data;
      if (index === 0) {
        picker.setColumnValues(1, list[value[0]]);
      }
    },
    /**
     * 确认时间类型
     * @param {*} e
     */
    onTimeConfirm(e) {
      const { value } = e.detail;
      this.setData({
        timeType: value,
        timePopupShow: false,
      });
      this.triggerEvent("timeConfirm", value);
    },
    /**
     * 确认市区
     * @param {*} e
     */
    onAreaConfirm(e) {
      const { value } = e.detail;
      this.setData({
        city: value[0],
        county: value[1],
        areaPopupShow: false,
      });
      this.triggerEvent("areaConfirm", value);
    },
    /**
     * 关闭弹窗
     */
    onCancel() {
      this.setData({
        timePopupShow: false,
        areaPopupShow: false,
      });
    },
  },
});
